#include <gtk/gtk.h>
#include <stdio.h>

#include "gtkutils.h"

#include "commandutils.h"

void sayHello() {
    printf("hello word\n");
}


enum {
    ACTION_NAME,
    ACTION_EXEC
};

struct AdbAction {
    char name[100];
    char exec[100];
} AdbActions[] = {
    {.name = "设备列表",            .exec = "adb devices"},
    {.name = "启动服务",            .exec = "adb start-server"},
    {.name = "杀死服务",            .exec = "adb kill-server"},
    {.name = "切换usb模式",         .exec = "adb usb"},
    {.name = "切换tcp模式(5555)",   .exec = "adb tcpip 5555"},
    {.name = "重启设备",            .exec = "adb reboot"},
};

createCellLayoutDataFunc(comb_action_data) {

}

GtkListStore *comb_action_list;

createTreeModelFunc(comb_action_model) {
    GtkTreeIter iter;
    for (int i=0; i < (sizeof(AdbActions)/sizeof(struct AdbAction)); i++) {
        listStoreAppend(comb_action_list, &iter);
        listStoreSet(comb_action_list, &iter,
            ACTION_NAME, AdbActions[i].name,
            ACTION_EXEC, AdbActions[i].exec,
            -1
        );
        printf("添加了: (%s), 可执行: (%s)\n", AdbActions[i].name, AdbActions[i].exec);
    }
    return convTreeModel(comb_action_list);
}

createSignalObjectFunc(click_exec_button, GtkComboBox) {
    GtkTreeIter iter;
    if (getComboBoxActiveIter(user_data, &iter)) {
        char *name = NULL, *exec = NULL;
        treeModelGet(convTreeModel(comb_action_list), &iter, 
            ACTION_NAME, &name, 
            ACTION_EXEC, &exec, -1);
        printf("点击了: (%s), 准备执行: (%s)\n", name, exec);
        if (exec) {
            int r = system(exec);
            int es = CMD_EXIT_STATUS(r);
            int e = CMD_IS_EXIT(r);
            printf("执行结果: %d, %d, %d\n", r,es,e);
        }
    }
}

static void activate(GtkApplication *app, gpointer user_data) {
    GtkWindow *window;

    window = createWindowWithTitleSize(app, "gtk-adb-mamanger", 400, 200);
    
    comb_action_list= createListStore(2, G_TYPE_STRING, G_TYPE_STRING);

    GtkComboBox *comb = createComboBoxWithModelFuncUnrefActive(comb_action_model, 0);
    GtkCellRendererText *renderer = createCellRendererText();
    setCellLayout(comb, renderer, "text", ACTION_NAME, comb_action_data, false);

    GtkBox *mainBox = createBoxWithVerticalAppends(5, 
        createBoxWithHorizntalMarginAlignAppends(5, 5, ACENTER,
            createLabel("adb 操作:"),
            comb,
            createButtonAction(comb, "执行", click_exec_button),
            NULL
        ),
        NULL
    );
    setWindowChild(window, mainBox);
    showWindow(window);
}

int	main(int argc, char **argv) {

    GtkApplication *app;
    int status;

    app = createApplicationConnectActivate("gtk.example.template", 
                                G_APPLICATION_FLAGS_NONE, activate);

    status = runApplication(app, argc, argv);
    objectUnref(app);

    return status;
}

